import 'package:flutter/material.dart';
import 'package:flutter_draggable_gridview/flutter_draggable_gridview.dart';
import 'package:flutter_project/common/utils/screen_size_utils.dart';
import 'package:flutter_project/config/app_bar_view.dart';
import 'package:flutter_project/config/theme_color.dart';
import 'package:get/get.dart';

import 'home_category_choose_controller.dart';

class HomeCategoryChoosePage extends StatefulWidget {
  const HomeCategoryChoosePage({super.key});

  @override
  State<HomeCategoryChoosePage> createState() => _HomeCategoryChoosePageState();
}

class _HomeCategoryChoosePageState extends State<HomeCategoryChoosePage> {
  final HomeCategoryChooseController bindController =
      Get.put(HomeCategoryChooseController());
  List<String> channelList = [
    "推荐",
    '视频',
    '直播',
    '文化',
    "明星",
    '情感',
    '职场',
    '美食',
    "游戏",
    '搞笑',
    '头像',
    '绘画',
    "音乐",
    '动漫',
    '手工',
    '壁纸',
    "摄影",
    '汽车',
    '穿搭',
    '家装',
    "旅行",
    '舞蹈',
    '母婴',
    '影视'
  ];

  List<CategoryModel> dataList = [];

  List<String> recommendList = [
    "萌宠",
    '学习',
    '科技数码',
    "竞争体育",
    '家居',
    '文具手帐',
    '潮鞋',
    "读书",
    '男士理容',
    '婚礼',
    '母婴',
    "户外",
    '影视',
    '科学科普',
    '露营',
    "护肤",
    '校园生活',
    '潮玩手办',
    '运动',
    "社科",
    '减脂',
    '心理',
    '综艺',
    '健身塑型'
  ];

  @override
  Widget build(BuildContext context) {
    return CommonAppWidget.navAppBar(
      title: '筛选',
      childWidget: SingleChildScrollView(
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 10),
          color: Colors.white,
          child: Column(
            children: [
              const SizedBox(
                height: 20,
              ),
              GetBuilder(
                  id: bindController.clickChannelId,
                  builder: (HomeCategoryChooseController homeController) {
                    return Row(
                      children: [
                        const Text(
                          '我的频道',
                          style: TextStyle(fontSize: 17),
                        ),
                        const SizedBox(
                          width: 10,
                        ),
                        Text(
                          homeController.isEdit ? '长按拖动排序' : '点击进入频道',
                          style: TextStyle(color: ThemeColor.textColorSecond),
                        ),
                        const Spacer(),
                        GestureDetector(
                          onTap: () {
                            bindController.isEdit = !bindController.isEdit;
                            bindController.update([
                              bindController.clickChannelId,
                              bindController.myChannelId
                            ]);
                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 10, vertical: 3),
                            decoration: BoxDecoration(
                                color: ThemeColor.sendMsgColor,
                                borderRadius: BorderRadius.circular(20)),
                            child: Text(
                              homeController.isEdit ? '完成编辑' : '进入编辑',
                              style: const TextStyle(color: Colors.blue),
                            ),
                          ),
                        ),
                      ],
                    );
                  }),
              const SizedBox(
                height: 20,
              ),
              GetBuilder(
                  id: bindController.myChannelId,
                  builder: (HomeCategoryChooseController homeController) {
                    return DraggableGridViewBuilder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 4,
                              crossAxisSpacing: 5,
                              mainAxisSpacing: 0,
                              childAspectRatio: 2 / 1),
                      children: getDataListWidget(),
                      dragCompletion: onDragAccept,
                      isOnlyLongPress: true,
                      dragFeedback: feedback,
                      dragPlaceHolder: placeHolder,
                    );
                  }),
              const SizedBox(
                height: 20,
              ),
              Row(
                children: [
                  const Text(
                    '推荐频道',
                    style: TextStyle(fontSize: 17),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Text(
                    '点击添加频道',
                    style: TextStyle(color: ThemeColor.textColorSecond),
                  ),
                ],
              ),
              const SizedBox(
                height: 20,
              ),
              GetBuilder(
                  id: bindController.addChannelId,
                  builder: (HomeCategoryChooseController homeController) {
                    return GridView.builder(
                      shrinkWrap: true,
                      itemCount: recommendList.length,
                      physics: const NeverScrollableScrollPhysics(),
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 4,
                              crossAxisSpacing: 10,
                              mainAxisSpacing: 10,
                              childAspectRatio: 2 / 1),
                      itemBuilder: (BuildContext context, int index) {
                        String name = recommendList[index];
                        return GestureDetector(
                          onTap: () {
                            recommendList.remove(name);
                            CategoryModel itemModel = CategoryModel();
                            itemModel.name = name;
                            dataList.add(itemModel);
                            bindController.update([
                              bindController.myChannelId,
                              bindController.addChannelId
                            ]);
                          },
                          child: Container(
                            key: ValueKey(name),
                            alignment: Alignment.center,
                            padding: const EdgeInsets.symmetric(vertical: 0),
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(4),
                                border: Border.all(
                                    color: ThemeColor.lineColor, width: 1.0)),
                            child: RichText(
                              text: TextSpan(
                                  text: '+ ',
                                  style: TextStyle(
                                      color: ThemeColor.textColorSecond,
                                      fontSize: 14),
                                  children: [
                                    TextSpan(
                                      text: recommendList[index],
                                      style: const TextStyle(
                                          fontSize: 14, color: Colors.black),
                                    ),
                                  ]),
                            ),
                          ),
                        );
                      },
                    );
                  }),
              const SizedBox(
                height: 20,
              ),
            ],
          ),
        ),
      ),
    );
  }

  void onDragAccept(
      List<DraggableGridItem> list, int beforeIndex, int afterIndex) {
    debugPrint('onDragAccept: $beforeIndex -> $afterIndex');
    CategoryModel temp = dataList[beforeIndex];
    dataList[beforeIndex] = dataList[afterIndex];
    dataList[afterIndex] = temp;
  }

  PlaceHolderWidget placeHolder(List<DraggableGridItem> list, int index) {
    return PlaceHolderWidget(
      child: Container(
        color: Colors.white,
      ),
    );
  }

  Widget feedback(List<DraggableGridItem> list, int index) {
    double itemWidth =
        (ScreenSizeUtils.deviceScreenWidth(context) - 15 * 3 - 20) / 4;
    return SizedBox(
      width: itemWidth,
      height: itemWidth / 2.0,
      child: list[index].child,
    );
  }

  @override
  void initState() {
    super.initState();
    bindController.isEdit = false;
    initData();
  }

  initData() {
    for (String element in channelList) {
      CategoryModel model = CategoryModel();
      model.name = element;
      dataList.add(model);
    }
  }

  List<DraggableGridItem> getDataListWidget() {
    List<DraggableGridItem> widgetList = [];
    for (CategoryModel element in dataList) {
      widgetList.add(DraggableGridItem(
        isDraggable: bindController.isEdit,
        child: Stack(
          key: ObjectKey(element),
          children: [
            Positioned(
              right: 7.5,
              top: 7.5,
              left: 0,
              child: Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.symmetric(vertical: 5),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4),
                    border:
                        Border.all(color: ThemeColor.lineColor, width: 1.0)),
                child: Text(element.name),
              ),
            ),
            Positioned(
              right: 0,
              top: 0,
              child: Visibility(
                visible: bindController.isEdit,
                child: GestureDetector(
                  onTap: () {
                    recommendList.add(element.name);
                    dataList.remove(element);
                    bindController.update([
                      bindController.myChannelId,
                      bindController.addChannelId
                    ]);
                  },
                  child: Container(
                      decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: ThemeColor.textColorSecond),
                      child: const Icon(
                        Icons.close,
                        color: Colors.white,
                        size: 15,
                      )),
                ),
              ),
            )
          ],
        ),
      ));
    }
    return widgetList;
  }
}

class CategoryModel {
  String name = '';
  bool isEdit = false;
}
